package org.lanqiao.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.lanqiao.gateway.config.MyPropertiesConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;

/**
 * 验证请求是否携带token
 * 需求：
 * 在这个全局的过滤器中，能够验证jwtToken 并且结合白名单进行过滤
 */
@Slf4j
@Component
public class TokenValidGlobalFilter    implements GlobalFilter , Ordered {

    @Autowired
    MyPropertiesConfig propertiesConfig;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.debug("请求{} 进入过滤器",exchange.getRequest().getPath(),exchange.getRequest().getURI());

        log.debug("白名单的Urls是{}", Arrays.toString(propertiesConfig.getWhiteURIS().toArray()));
        log.debug("白名单第一个的Urls是{}", propertiesConfig.getWhiteURIS().get(0));

        if(propertiesConfig.getWhiteURIS().contains(exchange.getRequest().getURI())){
            return chain.filter(exchange);  //执行下一个过滤器  表示放行
        }
        HttpHeaders   httpHeaders = exchange.getRequest().getHeaders();
        String  token  =httpHeaders.getFirst("Authorization");

        //验证token是否合法
       if(!"lanqiao".equals(token)){
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return  exchange.getResponse().setComplete();  //验证不合法
        }

        return chain.filter(exchange);  //执行下一个过滤器  表示放行
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
